package com.xizimall.rest.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.xizimall.mapper.TbItemCatMapper;
import com.xizimall.pojo.TbItemCat;
import com.xizimall.pojo.TbItemCatExample;
import com.xizimall.pojo.TbItemCatExample.Criteria;
import com.xizimall.rest.dao.JedisClient;
import com.xizimall.rest.pojo.CatNode;
import com.xizimall.rest.pojo.CatResult;
import com.xizimall.rest.service.ItemCatService;
import com.xizimall.common.utils.JsonUtils;

import redis.clients.jedis.JedisPool;
/**\
 * 商品分类服务
 * <p>Title: ItemCatServiceImpl</p>
 * <p>Description: </p>
 * <p>华南理工大学研究生</p> 
 * @author	李隆熹
 * @date	2018年4月17日下午9:38:18
 * @version 1.0
 */
@Service
public class ItemCatServiceImpl implements ItemCatService {
    
	@Autowired
	private TbItemCatMapper itemCatMapper;
	
	@Autowired
   private JedisClient jedisClient;
	
	@Value("${INDEX_ITEMCAT_REDIS_KEY}")
	private String INDEX_ITEMCAT_REDIS_KEY;
   
	@Override
	public CatResult getItemCatList() {
		CatResult catResult=new CatResult();
		catResult.setData(getCatList(0));
		return catResult;
	}
/**
 * 查询分类列表
 * <p>Title: getCatList</p>
 * <p>Description: </p>
 * @param i
 * @return
 */
	private List<?> getCatList(long parentId) {
		
		//创建查询条件
		TbItemCatExample example=new TbItemCatExample();
		Criteria criteria=example.createCriteria();
		criteria.andParentIdEqualTo(parentId);
		List<TbItemCat>list=itemCatMapper.selectByExample(example);
		//返回值list
		List resultList=new ArrayList<>();
		//向list中添加节点
		int count=0;
		for(TbItemCat itemCat:list){
			//判断是否为父节点
			if(itemCat.getIsParent()){
				CatNode catNode=new CatNode();
				if(parentId==0){
					catNode.setName("<a href='/products/"+
				itemCat.getId()+".html'>"+itemCat.getName()+"</a>");
				}
				else{
					catNode.setName(itemCat.getName());
				}
				catNode.setUrl("/products/"+itemCat.getId()+".html");
				catNode.setItem(getCatList(itemCat.getId()));
				
				resultList.add(catNode);
				count++;
				if(parentId==0&&count>=14){
					break;
				}
				
			//如果是子节点
			}else{
				resultList.add("/products/"+itemCat.getId()+".html|" + itemCat.getName());
			}
		}
		try {
			String cacheString=JsonUtils.objectToJson(resultList);
			jedisClient.hset(INDEX_ITEMCAT_REDIS_KEY, parentId+"", cacheString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultList;
	}

}
